/*************************************************************************
	> File Name: tcp_client.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/04 16:23
 ************************************************************************/

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>
#include <unistd.h>

const int SIZE = 1024;

uint16_t serverport;
std::string serverip;

static void usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << " port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        usage(argv[0]);
        exit(1);
    }
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        std::cout << "sock error, " << errno << ":" << strerror(errno) << std::endl;
        exit(2);
    }
    serverport = atoi(argv[2]);
    serverip = argv[1];
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    if (connect(sock, (struct sockaddr*)&server, sizeof server) < 0) {
        std::cout << "connect error, " << errno << ":" << strerror(errno) << std::endl;
        exit(3);
    }
    std::cout << "connect success" << std::endl;
    std::string cmd_line;
    char buffer[SIZE];
    while (1) {
        memset(&buffer, 0, sizeof buffer);
        std::cout << "Please input command:" << std::endl;
        std::getline(std::cin, cmd_line);
        write(sock, cmd_line.c_str(), cmd_line.size());
        read(sock, buffer, sizeof buffer - 1);
        std::cout << "execute result:" << buffer << std::endl;
    }
    close(sock);
    return 0;
}

